package com.itboye.pondteam.pondteam;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.itboye.pondteam.R;
import com.itboye.pondteam.app.MyApplication;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.DeviceListBean;
import com.itboye.pondteam.bean.SearchDeviceInfo;
import com.itboye.pondteam.db.DBManager;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.pondteam.utils.EmptyUtil.getSp;

public class LocalAreaDeviceActivity extends BaseActivity  implements Observer {

    private MyApplication mApp;
    ListView mListView;
    Context mContext;
    SearchDeviceInfo mSelectDeviceInfo;
    TextView txt_title;
    UserPresenter userPresenter;
    private ArrayList<HashMap<String, Object>> listItems;
    ImageView img_back;
    DBManager dbManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_area_device);
        mApp = (MyApplication) getApplication();
        mApp.mLocalAreaDevice = this;
        mContext = this;
        dbManager=new DBManager(this);
        txt_title.setText(getString(R.string.LAN_DEVICE));
        mSelectDeviceInfo = null;
        userPresenter = new UserPresenter(this);
        mListView = (ListView) findViewById(R.id.add_device_listView);
        // 列表项短按键处理
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectDeviceInfo = mApp.mLanDeviceList.get(position);
                if (deviceIsAdd(mSelectDeviceInfo)) {
                    new AlertDialog.Builder(mContext)
                            .setTitle(getString(R.string.tips))
                            .setMessage(getString(R.string.lan_tips))
                            .setPositiveButton(getString(R.string.ok), null)
                            .show();
                    return;
                }
                new AlertDialog.Builder(mContext)
                        .setTitle(getString(R.string.tips))
                        .setMessage(getString(R.string.make_sure_adddevice))
                        .setPositiveButton(getString(R.string.cancel), null)
                        .setNegativeButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                                mApp.addDevice(mSelectDeviceInfo);
                                userPresenter.addDevice(getSp(Const.UID), mSelectDeviceInfo.getDid(), mSelectDeviceInfo.getRes());
                                refreshDeviceList();
                            }
                        })
                        .show();
            }
        });
        refreshDeviceList();
    }


    public boolean deviceIsAdd(SearchDeviceInfo deviceInfo) {
        for (int i = 0; i < listItems.size(); i++) {
            String did = listItems.get(i).get("ItemState2").toString();
            if (did.equalsIgnoreCase(getString(R.string.alreayAdd))) {
//                deviceInfo.set = d.mDeviceName;
                return true;
            }
        }
        return false;
    }

    /**
     * 刷新局域网设备列表
     */
    public void refreshDeviceList() {
        listItems = new ArrayList<>();
        for (int i = 0; i < mApp.mLanDeviceList.size(); i++) {
            boolean hasAdd = false;
            SearchDeviceInfo deviceInfo = mApp.mLanDeviceList.get(i);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("ItemDid", "DID : " + deviceInfo.getDid());
            if (mApp.deviceListActivityUI.arrayList.size() > 0) {
                for (int i1 = 0; i1 < mApp.deviceListActivityUI.arrayList.size(); i1++) {
                    DeviceListBean deviceInfoInner = mApp.deviceListActivityUI.arrayList.get(i1);
                    if (deviceInfoInner.getDid().equals(deviceInfo.getDid())) {
                        hasAdd = true;
                        break;
                    } else {
                        hasAdd = false;
                    }
                }
            }
            if (deviceInfo.getDid().startsWith("S01")) {
                //过滤桶
                map.put("ItemIcon", R.drawable.device_chitangguolv);
            } else if (deviceInfo.getDid().startsWith("S02")) {
                //加热棒
                map.put("ItemIcon", R.drawable.device_jiarebang);
            } else if (deviceInfo.getDid().startsWith("S03")) {
                //变频水泵
                map.put("ItemIcon", R.drawable.device_shuibeng);
            } else if (deviceInfo.getDid().startsWith("S04")) {

            } else if (deviceInfo.getDid().startsWith("S05")) {

            } else {
                map.put("ItemIcon", R.drawable.ic_aplacher);
            }
            if (!hasAdd) {
                map.put("ItemState1", getString(R.string.unAdd));
                map.put("ItemState2", "");
            }else{
                map.put("ItemState1", "");
                map.put("ItemState2", getString(R.string.alreayAdd));
            }
            map.put("ItemName", deviceInfo.getDid());
            map.put("ItemRightArrow", null);
            listItems.add(map);
        }
        SimpleAdapter listItemsAdapter = new SimpleAdapter(this, listItems, R.layout.device_item,
                new String[]{"ItemName", "ItemDid", "ItemState1", "ItemState2", "ItemRightArrow", "ItemIcon"},
                new int[]{R.id.textView_dev_name, R.id.textView_dev_did, R.id.textView_dev_state1, R.id.textView_dev_state2, R.id.imageView_dev_right_arrow, R.id.imageView_dev_logo});
        mListView.setAdapter(listItemsAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
        }
    }

    @Override
    public void update(Observable o, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getCode() != 0) {
                MAlert.alert(entity.getMsg());
                return;
            }
            if (entity.getEventType() == UserPresenter.adddevice_success) {
                MAlert.alert(entity.getData());
                long re=dbManager.insertDeviceData(mSelectDeviceInfo.getDid(),mSelectDeviceInfo.getPwd(),getSp(Const.UID));
//                if (re>0) {
//                    MAlert.alert("success");
                    finish();
//                }
            } else if (entity.getEventType() == UserPresenter.adddevice_success) {
                MAlert.alert(entity.getData());
            }
        }
    }
}
